package com.cfm.bombercool 
{
	import mx.core.FlexSprite;
	import org.flixel.*;
	
	/**
	 * ...
	 * @author devninja
	 */
	public class PlayState extends FlxState
	{
		[Embed(source = "../../../../assets/sprites/bomberman.png")]
		public var BombermanSheet:Class;
		
		[Embed(source="../../../../assets/sprites/tiles.png")]
		public var TilesPNG:Class;
		
		[Embed(source="../../../../assets/sprites/oldsheet.gif")]
		public var GeneralPNG:Class;
		
		[Embed(source="../../../../assets/sprites/Gfx.png")]
		public var GfxPNG:Class;
		
		public var level:Level;
		public var player:Bomberman;
		public var bombs:FlxGroup;
		public var enemies:FlxGroup;
		
		override public function create():void
		{
			FlxG.bgColor = 0xffaaaaaa;
			
			level = new Level(this);
			add(level);
			
			bombs = new FlxGroup();
			add(bombs);
			player = new Bomberman(this, 16, 16);
			add(player);
			
			enemies = new FlxGroup();
			add(enemies);
			
			var numEnemiesTest:int = 10;
			for (var i:int = 0; i < numEnemiesTest; i++)
				spawnEnemy( (int) (Math.random() * 8) );
		}
		
		override public function update():void {
			super.update();
			FlxG.collide(level, player);
		}
		
		public function detonate(bomb:Bomb):void {
			var exp:Explosion = new Explosion(this, bomb.power);
			exp.x = bomb.x;
			exp.y = bomb.y;
			add(exp);
			
			bombs.remove(bomb, true);
			
			//Check if there are enemies nearby
			for each(var enemy:Enemy in enemies.members) {
				if ( Math.abs(enemy.x - exp.x) <= 16 && Math.abs(enemy.y - exp.y) <= 16 ){
					enemy.die();
				}
			}
		}
		
		public function dropBomb():void {				
			var bomb:Bomb = new Bomb(this, player.power, 1.5);
			bomb.x = 16 * (int) ( (player.x + 8)/ 16);
			bomb.y = 16 * (int) ( (player.y + 10) / 16);
			bombs.add(bomb);
		}
		
		public function spawnEnemy(type:int) {
			var enemy:Enemy = new Enemy(this, type);
			
			var x:int = Math.random() * 16;
			var y:int = Math.random() * 9;
			
			enemy.x = x * 16;
			enemy.y = y * 16;
			
			enemies.add(enemy);
		}
	}
}